package com.epfresh.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.ImageView;

import com.epfresh.R;
import com.epfresh.activity.CommonStoreActivity;
import com.epfresh.activity.MoreAreaStoreActivity;
import com.epfresh.activity.SearchStoreActivityNew;
import com.epfresh.adapter.AreaStoreViewBinder;
import com.epfresh.adapter.SingleAreaViewBinder;
import com.epfresh.adapter.VisitMarketTitleViewBinder;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.MerchantEntity;
import com.epfresh.bean.TypeBean;
import com.epfresh.global.BaseFragment;
import com.epfresh.views.MultiStateView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;

/**
 * Author: Chen
 * Date: 2019/1/30
 * Desc:
 */
public class MarketMerchantFragment extends BaseFragment implements View.OnClickListener{
    private MultiStateView msv_view;
    private RecyclerView rv_merchant_list;
    private GridLayoutManager gridLayoutManager;
    private RecyclerView.SmoothScroller smoothScroller;

    private MultiTypeAdapter multiAdapter;
    private List<Object> items = new ArrayList<>();
    private PtrFrameLayout ptrFrameLayout;

    private boolean requestDialogFlag = true;
    private String marketId;

    private ImageView ivBottom;
    private int flagPosVisitBtn = -1;
    private View ll_bottom;
    private GridView gv_bottom;

    private TopDepartAdapter bottomAdapter;
    private List<MerchantEntity.AreaBean> bottomList = new ArrayList<>();

    @Override
    public String getBaseTag() {
        return "marketMerchantFragment";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initIntent();
        return inflater.inflate(R.layout.fragment_merchant_market, container, false);
    }

    private void initIntent() {
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            marketId = bundle.getString("marketId");
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView(view);
        reqMerchantsList();
    }

    private void initView(View view) {
        ivBottom = view.findViewById(R.id.iv_bottom);
        ivBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ll_bottom.getVisibility() == View.VISIBLE) {
                    ll_bottom.setVisibility(View.GONE);
                    ll_bottom.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_bottom_out));

                    ivBottom.setImageResource(R.mipmap.market_show);
                } else {
                    ll_bottom.setVisibility(View.VISIBLE);
                    ll_bottom.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_bottom_in));

                    ivBottom.setImageResource(R.mipmap.market_close);
                }
            }
        });
        ll_bottom = view.findViewById(R.id.ll_bottom);
        gv_bottom = view.findViewById(R.id.gv_bottom);

        msv_view = view.findViewById(R.id.msv_view);
        msv_view.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        msv_view.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_EMPTY);
        msv_view.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);
        msv_view.setOnErrorClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refresh();
            }
        });
        rv_merchant_list = view.findViewById(R.id.rv_merchant_list);
        multiAdapter = new MultiTypeAdapter();

        ptrFrameLayout = view.findViewById(R.id.ptr_frame_layout);
        ptrFrameLayout.setPtrHandler(ptrHandler);

        VisitMarketTitleViewBinder visitMarketTitleViewBinder = new VisitMarketTitleViewBinder();
        SingleAreaViewBinder singleAreaViewBinder = new SingleAreaViewBinder();
        AreaStoreViewBinder areaStoreViewBinder = new AreaStoreViewBinder();

        multiAdapter.register(String.class, visitMarketTitleViewBinder);
        multiAdapter.register(MerchantEntity.AreaBean.class, singleAreaViewBinder);
        multiAdapter.register(MerchantEntity.AreaBean.StoresBean.class, areaStoreViewBinder);
        areaStoreViewBinder.setMoreStoreClickListener(new AreaStoreViewBinder.OnMoreStoreClickListener() {
            @Override
            public void onMoreStoreClick(String areaId) {
                Intent intent = new Intent(getAppActivity(), MoreAreaStoreActivity.class);
                intent.putExtra("marketId", marketId);
                intent.putExtra("areaId", areaId);
                startActivity(intent);
            }

            @Override
            public void onItemClick(MerchantEntity.AreaBean.StoresBean item) {
                Intent storeIntent = new Intent(getAppActivity(), CommonStoreActivity.class);
                storeIntent.putExtra("storeId",item.getId());
                storeIntent.putExtra("from","MarketMerchantFragment");
                startActivity(storeIntent);
            }
        });

        multiAdapter.setItems(items);
        gridLayoutManager = new GridLayoutManager(getAppActivity(), 5);
        GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object item = items.get(position);
                return (item instanceof MerchantEntity.AreaBean) ? 1 : 5;
            }
        };
        gridLayoutManager.setSpanSizeLookup(spanSizeLookup);
        rv_merchant_list.setLayoutManager(gridLayoutManager);
        rv_merchant_list.setAdapter(multiAdapter);

        rv_merchant_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int firstVisibleItemPosition = gridLayoutManager.findFirstVisibleItemPosition();
                if (flagPosVisitBtn != -1 && firstVisibleItemPosition >= flagPosVisitBtn) {
                    if (ivBottom.getVisibility() == View.GONE) {
                        ivBottom.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (ivBottom.getVisibility() == View.VISIBLE) {
                        ivBottom.setVisibility(View.GONE);
                        ivBottom.setImageResource(R.mipmap.market_show);
                    }
                    if (ll_bottom.getVisibility() == View.VISIBLE) {
                        ll_bottom.setVisibility(View.GONE);
                    }
                }
            }
        });

        bottomAdapter = new TopDepartAdapter(getAppActivity(), bottomList, R.layout.item_depart_text);
        gv_bottom.setAdapter(bottomAdapter);

        smoothScroller = new LinearSmoothScroller(getAppActivity()) {
            @Override
            protected int getVerticalSnapPreference() {
                return LinearSmoothScroller.SNAP_TO_START;
            }
        };

        singleAreaViewBinder.setOnAreaClickListener(new SingleAreaViewBinder.OnAreaClickListener() {
            @Override
            public void onAreaClick(MerchantEntity.AreaBean item) {
                int index = items.indexOf(item.getStores().get(0));
                smoothScroller.setTargetPosition(index);
                gridLayoutManager.startSmoothScroll(smoothScroller);
            }
        });
    }

    /**
     * 刷新
     */
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv_merchant_list, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    public void refresh() {
        reqMerchantsList();
    }

    private void reqMerchantsList() {
        RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(AppPurchaseRouterConstant.cmd_merchant);
        requestEntity.putParameter("id", marketId);

        request(requestEntity, AppPurchaseRouterConstant.cmd_merchant, new OnRequestListener<MerchantEntity>() {
            @Override
            public MerchantEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, MerchantEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
                ptrFrameLayout.refreshComplete();
                msv_view.setViewState(MultiStateView.VIEW_STATE_ERROR);

            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
                ptrFrameLayout.refreshComplete();
                msv_view.setViewState(MultiStateView.VIEW_STATE_ERROR);
            }

            @Override
            public void onStart(Object tag) {
                if (requestDialogFlag) {
                    requestDialogFlag = false;
                    msv_view.setViewState(MultiStateView.VIEW_STATE_LOADING);
                }

            }

            @Override
            public void onResponse(ResponseEntity<MerchantEntity> response, Object tag) {
                ptrFrameLayout.refreshComplete();
                if (response.getResponseElement() != null) {
                    items.clear();
                    if (response.getResponseElement().getMarketAreas() != null && response.getResponseElement().getMarketAreas().size() > 0) {
                        items.add("");
                        items.addAll(response.getResponseElement().getMarketAreas());

                        bottomList.clear();
                        bottomList.addAll(response.getResponseElement().getMarketAreas());

                        int size = response.getResponseElement().getMarketAreas().size();
                        if (size % 5 != 0) {
                            int spaceSize = 5 - size % 5;
                            for (int i = 0; i < spaceSize; i++) {
                                MerchantEntity.AreaBean areaBean = new MerchantEntity.AreaBean();
                                items.add(areaBean);
                            }
                        }
                        flagPosVisitBtn = items.size();

                        for (MerchantEntity.AreaBean areaBean : response.getResponseElement().getMarketAreas()) {
                            for (int i = 0; i < areaBean.getStores().size(); i++) {
                                if (response.getResponseElement().getMarketAreas().indexOf(areaBean) == response.getResponseElement().getMarketAreas().size() - 1) {
                                    if (i == areaBean.getStores().size() - 1) {
                                        areaBean.getStores().get(i).setLast(true);
                                    }
                                }
                                areaBean.getStores().get(0).setGroupName(areaBean.getName());
                                areaBean.getStores().get(0).setHaveMore(areaBean.isMore());
                                items.add(areaBean.getStores().get(i));
                            }
                        }
                    }

                    msv_view.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    multiAdapter.notifyDataSetChanged();
                    bottomAdapter.notifyDataSetChanged();
                } else {
                    msv_view.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                }
            }
        });
    }


    class TopDepartAdapter extends CommonAdapter<MerchantEntity.AreaBean> {
        TopDepartAdapter(Context context, List<MerchantEntity.AreaBean> runPacks, int layoutId) {
            super(context, runPacks, layoutId);
        }

        @Override
        public void convert(ViewHolder holder, MerchantEntity.AreaBean areaBean) {
            if (areaBean == null) {
                holder.setText(R.id.tv_depart, "配送中心");
            } else {
                holder.setText(R.id.tv_depart, areaBean.getName());
            }
            holder.getView(R.id.tv_depart).setTag(R.id.item_key_status, areaBean);
            holder.setOnClickListener(R.id.tv_depart, MarketMerchantFragment.this);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_depart:
                if (v.getTag(R.id.item_key_status) instanceof MerchantEntity.AreaBean) {
                    MerchantEntity.AreaBean areaBean = (MerchantEntity.AreaBean) v.getTag(R.id.item_key_status);
                    int indexOf = items.indexOf(areaBean.getStores().get(0));
                    smoothScroller.setTargetPosition(indexOf);
                    gridLayoutManager.startSmoothScroll(smoothScroller);

                    if (ll_bottom.getVisibility() == View.VISIBLE) {
                        ll_bottom.setVisibility(View.GONE);
                        ivBottom.setImageResource(R.mipmap.market_show);
                    }
                }
                break;
        }
    }
}
